package LibraryManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;

public class Library {
    private ArrayList<String> Books;
    private ArrayList<String> Borrowed;
    private ArrayList<String> dates;
    private boolean isUserLogined;
    private String[] user;

    Library() {
        Books = new ArrayList<>();
        Borrowed = new ArrayList<>();
        dates = new ArrayList<>();
        user = new String[3];
    };
    public void setBook(String n){
        if(this.Books.size() == 1){
            if(this.Books.get(0)=="")
                this.Books.remove(0);
        }
        this.Books.add(n);
    }
    public Boolean FindLibrary(String s){
        boolean x;
        if(this.Books.size()==0){
            String r = "库中没有任何书籍";
            System.out.println(r);
        }
        x = false;
        for(int i = 0;i<this.Books.size();i++){
            if(this.Books.get(i).matches(s))
                x = true;
        }

        return x;
    }
    public int FindBorrowed(String s){
        int x = -1;
        int length = this.Borrowed.size();
        for(int i = 0; i<length;i++){
            if(this.Borrowed.get(i).equals(s)){
                x = i;
                break;
            }
        }
        return x;
    }
    public String returnBook(int x,String ss) throws FileNotFoundException {
        if(x!=-1){
            String s = this.Borrowed.get(x);
            this.Borrowed.remove(x);
            this.dates.remove(x);
        }
        File f = new File("NewBook.txt");
        PrintWriter r = new PrintWriter(f);
        r.print(ss);
        r.print(" ");
        r.close();
        String result = "归还成功";
        return result;
    }
    public String borrowBook(String ss){
        String result = new String();
        //从book里查找本书籍
        for(int i = 0;i<this.Books.size();i++){
            //找到了
            if(this.Books.get(i).matches(ss)){
                //赋值给s
                String s = this.Books.get(i);
                //从Books里移除
                this.Books.remove(i);

                /*下面就将书名添加到借阅列表里，日期添加到dates列表里
                boorowed和dates列表是一一对应的
                   1.如果借阅列表长度为1，而且第零个元素为空
                       先删除空元素，再添加
                   2.长度不唯为一，直接添加
                */
                if(this.Borrowed.size() == 1&&this.Books.get(0).equals(""))
                {
                    //如果第零个元素为空，先删除这个空元素，再添加
                    this.Borrowed.remove(0);
                    this.dates.remove(0);
                    this.Borrowed.add(s);
                    this.dates.add(new Date().toString());
                    result = "借阅成功";
                }
                else {
                    this.Borrowed.add(s);
                    this.dates.add(new Date().toString());
                    result = "借阅成功";
                }
            }
        }
        return result;
    }
    public String deleteBook(String n){
        String r ="";
        System.out.println(n);
        if(this.Books.size()==0){
            r = "库中没有任何书籍";
            throw new NotFoundBookException();
        }
        for(int i =0 ;i<this.Books.size();i++)
        {
            System.out.println(this.Books.get(i));
            if(this.Books.get(i).matches(n))
            {
                r += '"'+this.Books.get(i)+'"'+"书籍已移除";
                this.Books.remove(i);
                break;
            }
            else {
                r = "未找到相关书籍";
            }
        }
        return r;
    }
    public void printList(){
        System.out.println(Books.size());
        for(int i = 0; i<Books.size();i++){
            System.out.println(i+"."+Books.get(i));
        }
    }
    public void cleanLibrary(){
        System.out.println("已清理"+this.Books.size()+"个图书");
        this.Books.clear();
    }
    public void ReadData() throws FileNotFoundException {
        File f = new File("Library.txt");
        File f2 = new File("borrowedRecord.txt");
        Scanner s = new Scanner(f);
        Scanner s2 =  new Scanner(f2);
        while(s.hasNext()){
            this.Books.add(s.nextLine());
        }
        //System.out.println(s2.nextLine());
        while(s2.hasNext()){
            String[] c = s2.nextLine().split(" ");
            if(c[9].equals("已借阅")) {
                this.Borrowed.add(c[8]);
                String str  = c[2]+" ";
                       str += c[3]+" ";
                       str += c[4]+" ";
                       str += c[5]+" ";
                       str += c[6]+" ";
                       str += c[7]+" ";
                this.dates.add(str);
            }
//            else if(c[9].equals("已归还")){}
//            for(String n:c) {
//                System.out.println(n);
//            }
        }
    }
    public String RecordBooks() throws FileNotFoundException {
        String result = "";
        File d = new File("Library.txt");
        String[] ss = new String[this.Books.size()];

        for(int j =0;j<this.Books.size();j++){
            ss[j] = this.Books.get(j);
        }
        PrintWriter w = new PrintWriter(d);
        int n = 0;
        //遍历字符串数组，将所有书籍写入文件中
        for(String s : ss){
            w.print(ss[n]);
            w.println(' ');
            n++;
        }
         w.close();
        result = "已保存";
        return result;
    }
    public String recordBorrow(String s) throws FileNotFoundException {
        String result = "";
        /*找一下本书籍在借阅列表里的序号
        * 这样就方便查到借阅时间*/
        int x = 0;
        System.out.println(this.Borrowed.size());
        for(int i=0;i<Borrowed.size();i++){
            if(this.Borrowed.get(i).matches(s)){
                x = i;
            }
        }
        System.out.println(x);
        //按照x找出日期和书名
        String r  = this.dates.get(x).toString()+"  ";
               r += this.Borrowed.get(x)+" ";
               r += this.user[0];
               r += " 已借阅";
        //创建文件句柄
        File f = new File("borrowedRecord.txt");
        //创建文件扫描句柄
        Scanner filereader = new Scanner(f);
        //按行读取文件里的数据拼接成新的字符串s1
        String s1="";
        int m = 1;
        while(filereader.hasNext()){
            if(s1.equals("")){
                s1 = filereader.nextLine();
                s1 += '\n';
            }
            else {
                s1 += filereader.nextLine();
                s1 += '\n';
                m++;
            }
        }
        System.out.println(s1);
        //文件记录后面添加新的借阅登记信息
        s1 += m;
        s1 += " ";
        s1 += r;
        s1 += '\n';
        //将新的字符串写入文件里
        PrintWriter output = new PrintWriter(f);
        output.print(s1);
        output.close();
        //返回结果
        result = "借阅登记成功";
        return result;
    }
    public void printBorrowed(){
        for(int i = 0;i<this.Borrowed.size();i++){
            System.out.println(this.Borrowed.get(i));
        }
    }
    public String checkReturnTime(int m){
        String s="大约归还时间为：";
        String time1 = this.dates.get(m);
        System.out.println("借阅时间："+time1);
        String[] times = time1.split(" ");
        //System.out.println(times[1]);
        switch (times[1]){
            case "Jan":
                times[1] = "Feb";
                break;
            case "Feb":
                times[1] = "Mar";
                break;
            case "Mar":
                times[1] = "Apr";
                break;
            case "Apr":
                times[1] = "May";
                break;
            case "May":
                times[1] = "Jun";
                break;
            case "Jun":
                times[1] = "Jul";
                break;
            case "Jul":
                times[1] = "Aug";
                break;
            case "Aug":
                times[1] = "Sept";
                break;
            case "Sept":
                times[1] = "Oct";
                break;
            case "Oct":
                times[1] = "Nov";
                break;
            case "Nov":
                times[1] = "Dec";
                break;
            case "Dec":
                times[1] = "Jan";
                break;
            default:
                System.out.println("借阅时间格式错误，请联系管理员");
                break;
        }
        for(String a:times){
            s += a;
            s += " ";
        }
        return s;
    }
    public String checkUserReturnsTime() throws FileNotFoundException {
        String str;
        File f = new File("borrowedRecord.txt");
        Scanner d = new Scanner(f);
        String[] data= new String[10];
        int i = 0;
        while(d.hasNext()){
            str = d.nextLine();

            String[] s = str.split(" ");
            for(String x:s){
                 //System.out.println(x);
                 //System.out.println(this.user[0]);
                 if(x.equals(this.user[0])){
                     //System.out.println(str);
                     data[i] = str;
                     i++;
                     continue;
                 }
            }

        }
        for(String s:data){
            if(s==null) {
                break;
            }
            System.out.println(s);
        }
        str = "已查找所有借阅信息";
        return str;
    }
    public String recordReturn(String s,int n){
        String result = "";

        return result;
    }
    public String checkFile() throws FileNotFoundException {
        String s = "";
        File g = new File("NewBook.txt");
        Scanner h = new Scanner(g);
        if(g.exists()){
            while(h.hasNext()){
                //System.out.print(h.next()+" ");
                s += h.next();
                s += " ";
            }
        }
        return s;
    }
    public String clearNewBook() throws FileNotFoundException {
        String result;
        File f = new File("NewBook.txt");
        PrintWriter d = new PrintWriter(f);
        d.print(" ");
        d.close();
        result = "文件已清空";
        return result;
    }
    public String Register() throws FileNotFoundException {
        String result;
        Scanner input = new Scanner(System.in);
        String userName = "";
        String str = "";int n = 0;File f = new File("Users.txt");
        boolean userNameinvalid = true;
        while(userNameinvalid) {
            Scanner input1 = new Scanner(System.in);
            System.out.println("请输入用户名：");
            userName = input1.nextLine();

            Scanner ff = new Scanner(f);
            while (ff.hasNext()) {
                String xx = ff.nextLine();
                str += xx;
                str += "\n";
                n++;
                //System.out.print(str);
                String[] ss = xx.split(" ");
                if (ss[1].equals(userName)) {
                    System.out.println("用户名已被使用，请重新输入");
                    userName = input1.nextLine();
                } else {
                    userNameinvalid = false;
                }
            }
            ff.close();
        }
        System.out.println("请输入密码：");
        String passWord = input.nextLine();

        //System.out.println(str);
        str += n +". "+userName+" "+passWord;
        //System.out.print(str);
        PrintWriter r = new PrintWriter(f);
        r.print(str);
        r.close();
        result = "注册成功";
        return result;
    }
    public String Userslogin(int xx) throws FileNotFoundException {
        String result;
        Scanner in = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String userName = in.nextLine();
        System.out.println("请输入密码：");
        String passWord = in.nextLine();
        File f = new File("Users.txt");
        Scanner ff = new Scanner(f);
        String[][] ss = new String[100][4];
        int i = 0;
        while(ff.hasNext()){
            ss[i] = ff.nextLine().split(" ");
            i++;
        }
        ff.close();
        result = "密码错误";
        for(int k = 0;k< ss.length;k++){
            //如果为空，结束循环
            if(ss[k][0]==null){break;}
            //调试模式
            if(xx == 1) {
                for (int l = 0; l < ss[0].length; l++) {
                    if (ss[k][l] != null) {System.out.print(ss[k][l] + " ");}
                }System.out.println("");
            }

            if(passWord.equals(ss[k][2])&&userName.equals(ss[k][1])){
                result = "密码正确";
                this.isUserLogined = true;
                this.user[0] = userName;
                this.user[1] = passWord;
                this.user[2] = ss[k][3];
            }
        }
        return result;
    }
    public String userExit(){
        this.isUserLogined = false;
        this.user[0] = null;
        this.user[1] = null;
        return "账号已退出";
    }
    public String printUserInfo(){
        String str = "";
        str += "用户名："+this.user[0];
        str += "联系方式："+this.user[2];
        return str;
    }
    public void changeUserInfo(int i,String s){
        this.user[i] = s;
    }
    public String getOldUserName(){
        return this.user[0];
    }
    public String SaveUserInfo(String userName) throws FileNotFoundException {
        String name;
        if(userName.equals("")){
            name = this.user[0];
        }
        else{
            name = userName;
        }
        String result="";
        File f = new File("Users.txt");
        Scanner d = new Scanner(f);
        String[] info;
        String[] newUserInfo = new String[100];
        int index = 0;
        while(d.hasNext()){
            String s = d.nextLine();
            info = s.split(" ");
            if(info[1].equals(name)){
                //System.out.println("已找到用户信息");
                String ss  = info[0]+" ";
                       ss += this.user[0]+" ";
                       ss += this.user[1]+" ";
                       ss += this.user[2];
                //System.out.println(ss);
                newUserInfo[index] = ss;
                //System.out.println(newUserInfo[index]);
            }
            else {
                newUserInfo[index] = s;
            }
            index++;
        }
        d.close();
        String Write="";
        PrintWriter r = new PrintWriter(f);
        for(String l:newUserInfo){
            if(l==null){break;}
            Write += l;
            Write += '\n';
        }
        //System.out.print(Write);
        r.print(Write);
        r.close();
        return result;
    }

    public static void main(String []args) throws FileNotFoundException {
        System.out.println("欢迎来到图书馆管理系统。。。");
        //用来整数输入
        Scanner input = new Scanner(System.in);
        //用来字符串输入
        Scanner input2 = new Scanner(System.in);
        Library l = new Library();
        //从文件中读取数据，加载到Books列表里
        l.ReadData();
        //总开关状态变量
        boolean exit = true;
        while (exit) {
            int status = 0;
            while (status == 0) {
                String Lists = "1.管理员入口" + '\n';
                Lists += "2.借阅者入口" + '\n';
                Lists += "3.图书检索"+'\n';
                Lists += "4.退出";

                boolean isInvalid = true;
                while(isInvalid) {
                    try {
                        System.out.println(Lists);
                        status = input.nextInt();
                        isInvalid = false;
                    }catch(InputMismatchException ex){
                        System.out.println("输入有误，请输入正确指令");
                        input.nextLine();
                    }
                }
                if(status == 4){exit = false;break;}
            }
            while (status == 1) {
                String rs = l.checkFile();
                if(!rs.equals("")){
                    System.out.println("你有待入库书籍：");
                    System.out.println(rs);
                    System.out.println("是否进行一键入库？1.是  2.否");
                    int f = 0;
                    boolean invalid = true;
                    while(invalid) {
                        try {
                            f = input.nextInt();
                            invalid = false;
                        } catch (InputMismatchException ex) {
                             System.out.println("输入有误，请输入1，2");
                             input.nextLine();
                        }
                    }
                    if(f==1){
                        String[] d = rs.split(" ");
                        for(String s:d){l.setBook(s);}
                        System.out.println("入库成功");
                        System.out.println(l.clearNewBook());
                    }

                }
                System.out.println("1.图书入库");
                System.out.println("2.图书出库");
                System.out.println("3.查询库中的图书");
                System.out.println("4.清理库");
                System.out.println("5.退出");
                int n = input.nextInt();

                switch (n) {
                    case 1:
                        System.out.println("请输入入库的图书总数：");
                        boolean aa = true;
                        while (aa) {
                            try {
                                int count = input.nextInt();
                                for (int i = 0; i <= count; i++) {
                                    System.out.println("请输入书籍名称：");
                                    String x = input.nextLine();
                                    l.setBook(x);
                                }
                                aa = false;
                            } catch (InputMismatchException ex) {
                                System.out.println("输入有误，请重新输入");
                                input.nextLine();
                            }
                        }
                        break;
                    case 2:
                        boolean s = true;
                        while (s) {

                            try {
                                System.out.println("请输入要出库的图书名称");

                                String BookName = input2.nextLine();
                                System.out.println("图书名：" + BookName);
                                System.out.println(l.deleteBook(BookName));

                            } catch (NotFoundBookException ex) {
                                System.out.println("库中没有任何书籍");

                            } catch (InputMismatchException ex) {
                                System.out.println("输入有误");
                                input.nextLine();
                            }
                            System.out.println("是否继续出库？1.yes 2.no");
                            int x = input.nextInt();
                            if (x == 2) {
                                s = false;
                            }
                        }
                        break;
                    case 3:
                        System.out.println("以下是库中图书：");
                        l.printList();
                        break;
                    case 4:
                        l.cleanLibrary();
                        break;
                    case 5:
                        /*将库中书籍写入文件中，方便下次加载*/
                        System.out.println(l.RecordBooks());
                        status = 0;
                        break;
                    default:
                        break;
                }
            }
            while (status == 2) {
                //检测登陆状态，没登陆的话需要执行
                if (!l.isUserLogined) {
                    boolean Input = false;
                    while (!Input) {
                        try {
                            System.out.println("1.注册");
                            System.out.println("2.登录");
                            System.out.println("3.退出");
                            int n = input.nextInt();
                            if (n == 1) {
                                System.out.println(l.Register());
                            } else if (n == 2) {
                                //登录
                                String check = l.Userslogin(0);
                                System.out.println(check);
                                if (check.equals("密码正确")) {
                                    Input = true;
                                } else {
                                    System.out.println("用户名和密码错误");
                                }
                            } else {
                                status = 0;
                                break;
                            }
                        } catch (InputMismatchException ex) {
                            System.out.println("输入有误，请重新输入");
                            input.nextLine();
                        }
                    }
                } else if (l.isUserLogined) {
                    String visitorLists  = "1.书籍借阅" + '\n';
                           visitorLists += "2.书籍归还" + '\n';
                           visitorLists += "3.借阅时间查询" + '\n';
                           visitorLists += "4.图书检索"+"\n";
                           visitorLists += "5.返回" + '\n';
                           visitorLists += "6.个人信息"+'\n';
                           visitorLists += "7.退出登录";
                    System.out.println(visitorLists);
                    int bt = 0;
                    boolean ok = true;
                    while (ok) {
                        try {
                            bt = input.nextInt();
                            ok = false;
                        } catch (InputMismatchException ex) {
                            System.out.println("输入有误，请输入相应的数字");
                            input.nextLine();
                        }
                    }
                    switch (bt) {
                        case 1:
                        /*借阅书籍
                        1.首先查询，确认书籍是否存在
                        2.如存在，减少库存，记录借阅信息
                       */
                            System.out.println("请输入想要借阅的书籍名称：");
                            String ss = input2.nextLine();
                            System.out.println(ss);
                            boolean x = l.FindLibrary(ss);
                            //如果库中存在本书名，执行借阅并登记
                            if (x == true) {
                                System.out.println(l.borrowBook(ss));
                                System.out.println(l.recordBorrow(ss));
                            } else {
                                //如果不存在回到上一层循环
                                System.out.println("库中未找到你要的书籍，请前往图书检索来查询详情");
                            }
                            break;
                        case 2:
                            /*
                             * 书籍归还
                             * 查询借阅列表
                             *    1.如果在借阅列表里存在
                             *       删除借阅信息：
                             *            借阅列表里移除
                             *            日期里移除
                             *            将书名写入文件里，提供给管理员入库
                             *    2.如果不在借阅列表里
                             *        将书名写入文件里，提供给管理员入库
                             * */
                            System.out.println("请输入想要归还的书名：");
                            String s = input2.nextLine();
                            int ff = l.FindBorrowed(s);
                            System.out.println(ff);
                            System.out.println(l.returnBook(ff, s));
                            break;
                        case 3:
                            /*
                             * 查询归还时间
                             * 查询书籍借阅登记表，找到本用户的借阅数据
                             * */
                            l.printBorrowed();
                            System.out.println(l.checkUserReturnsTime());
                            break;
                        case 4:
                            /*图书检索功能
                            * 1.查询某书是否在库中存在
                            * 2.如果被借阅出去了，就查一下归还时间
                            * */
                            System.out.println("请输入要检索的书名：");
                            String bookName = input2.nextLine();
                            if(!l.FindLibrary(bookName)) {
                                int e = l.FindBorrowed(bookName);
                                if(e==-1){
                                    System.out.println("很抱歉，图书馆未入库本书");
                                }
                                else{
                                    System.out.println(l.checkReturnTime(e));
                                }
                            }
                            else{
                                System.out.println("本书库中已存在");
                            }
                            break;
                        case 5:
                            System.out.println(l.RecordBooks());
                            status = 0;
                            break;
                        case 6:
                            boolean xs = true;
                            while(xs) {
                                System.out.println(l.printUserInfo());
                                System.out.println("1.修改用户名");
                                System.out.println("2.修改密码");
                                System.out.println("3.补全联系方式");
                                System.out.println("4.返回");
                                int c = 0;
                                boolean invalid = true;
                                while (invalid) {
                                    try {
                                        c = input.nextInt();
                                        invalid = false;
                                    } catch (InputMismatchException ex) {
                                        System.out.println("输入有误，请重新输入");
                                        input.nextLine();
                                    }
                                }
                                if (c == 1) {/*修改用户名*/
                                    String oldUserName = l.getOldUserName();
                                    String M = input2.nextLine();
                                    l.changeUserInfo(0, M);
                                    l.SaveUserInfo(oldUserName);
                                } else if (c == 2) {/*修改密码*/
                                    String M = input2.nextLine();
                                    l.changeUserInfo(1, M);
                                } else if (c == 3) {/*补全联系方式*/
                                    String M = input2.nextLine();
                                    l.changeUserInfo(2, M);
                                } else if (c == 4) {/*返回上一步*/
                                    l.SaveUserInfo("");
                                    xs = false;
                                }
                            }
                            break;
                        case 7:
                            System.out.println(l.RecordBooks());
                            System.out.println(l.userExit());
                            status = 0;
                            break;
                        default:
                            System.out.println("输入有误，请输入相应的数字");
                            break;
                    }
                }
            }
            while (status == 3){
                /*图书检索
                * 本功能不用登陆就可以进行图书检索功能
                * 只提供一种功能，首先从库中查找，若找不到，则从借阅登记表里查询
                * 要么在库里，要么给用户显示归还时间，方便下次过来借阅*/
                System.out.println("1.图书检索功能");
                System.out.println("2.返回上一步");
                int d = 0;
                boolean isvalid = false;
                while(!isvalid){
                    try{
                         d = input.nextInt();
                         isvalid = true;
                    }catch(InputMismatchException ex){
                        System.out.println("输入有误，请输入正确指令");
                        input.nextLine();
                    }
                }
                if(d==1){
                    System.out.println("请输入想要搜索的书名：");
                    String bookName = input2.nextLine();
                    if(!l.FindLibrary(bookName)) {
                        int e = l.FindBorrowed(bookName);
                        if(e==-1){
                            System.out.println("很抱歉，图书馆未入库本书");
                        }
                        else{
                            System.out.println(l.checkReturnTime(e));
                        }
                    }
                    else{
                        System.out.println("本书库中已存在");
                    }
                }
                else if(d==2){
                    status = 0;
                    break;
                }
            }
        }
    }
}
